import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:hitutor/Util/DateUtil.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/Check.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';

import 'ChangePassword.dart';

class EditPersonalData extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _EditPersonalData();
  }
}

class _EditPersonalData extends State<EditPersonalData> {
  TextEditingController CNameController = TextEditingController();
  TextEditingController ENameController = TextEditingController();
  TextEditingController SkypeController = TextEditingController();
  TextEditingController PhoneController = TextEditingController();
  TextEditingController CEmailController = TextEditingController();
  TextEditingController AddrController = TextEditingController();

  String userId = "";
  String birthday = "";
  String birthday_utc = "";
  String sex = "";
  String email = "";

  selectBirthday() {
    DatePicker.showDatePicker(context,
        dateFormat: "yyyy年 MM月 dd日", //通过空格设置滚轮数量
        initialDateTime: DateTime(2000, 2, 2),
        pickerTheme: DateTimePickerTheme(confirm: Text("完成", style: TextStyle(fontSize: 14, color: MyColor.C58))),
        onConfirm: (DateTime dateTime, List<int> selectedIndex) {
      birthday = getStrTime(dateTime, DateUtil.YMD);
      birthday_utc = getUtcTime(dateTime);
      setState(() {});
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getUserData();
    });
    super.initState();
  }

  getUserData() {
    HttpGo(context).get("/Profile/GetProfile?studentId=${Global.studentId}", {}, (data) {
      userId = data["studentUserId"].toString();
      sex = data["sex"];
      email = data["email"];
      birthday = getStrTime(getTimeByUtc(data["birthday"]), DateUtil.YMD);
      birthday_utc = data["birthday"]??"";
      CNameController.text = data["studentName"]??"";
      ENameController.text = data["studentEngName"]??"";
      SkypeController.text = data["skype"]??"";
      CEmailController.text = data["calendarMail"]??"";
      PhoneController.text = data["contactNumber"]??"";
      AddrController.text = data["address"]??"";
      setState(() {});
    }, (code, error) => showToast(error));
  }

  updateUserData() {
    HttpGo(context).post("/Profile/UpdateProfile", {
      "studentId": Global.studentId,
      "studentName": CNameController.text,
      "studentEngName": ENameController.text,
      "skype": SkypeController.text,
      "sex": sex,
      "birthDay": birthday_utc,
      "contactNumber": PhoneController.text,
      "calendarMail": CEmailController.text,
      "address": AddrController.text
    }, (data) {
      PageUtil().back(context);
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return MyPage(
        "編輯個人資料",
        Container(
            color: MyColor.F8,
            child: SingleChildScrollView(
                child: Column(children: [
              Item(title: "使用者ID", child: Text("$userId", style: TextStyle(fontSize: 14, color: MyColor.C58))),
              Item(title: "中文姓名", child: NormalInput(hintText: "輸入中文姓名", controller: CNameController)),
              Item(title: "英文姓名", child: NormalInput(hintText: "輸入英文姓名", inputType: NormalInput.Email, controller: ENameController)),
              Item(title: "SKYPE帳號", child: NormalInput(hintText: "輸入SKYPE帳號", controller: SkypeController)),
              Container(height: 8),
              Item(
                  title: "性別",
                  child: SexChooser(
                      sex: sex,
                      onSexChoose: (sex) {
                        this.sex = sex;
                        setState(() {});
                      })),
              GestureDetector(
                  onTap: selectBirthday,
                  child: Item(
                      title: "生日",
                      child: TextBtn(birthday, alignment: Alignment.centerLeft, style: TextStyle(fontSize: 14, color: MyColor.C58)))),
              Item(title: "連絡電話", child: NormalInput(hintText: "輸入連絡電話", inputType: NormalInput.Phone, controller: PhoneController)),
              Item(
                  title: "電子信箱",
                  child: TextBtn(email, alignment: Alignment.centerLeft, style: TextStyle(fontSize: 14, color: MyColor.C58))),
              Item(title: "行事曆信箱", child: NormalInput(hintText: "輸入行事曆信箱", inputType: NormalInput.Email, controller: CEmailController)),
              Item(title: "通訊地址", child: NormalInput(hintText: "輸入通訊地址", controller: AddrController)),
              Container(height: 8),
              ChangePsw()
            ]))),
        rightWidgets: [
          TextBtn("完成",
              margin: EdgeInsets.only(right: 16),
              height: 40,
              style: TextStyle(fontSize: 14, color: MyColor.BlueHome),
              onTap: updateUserData)
        ]);
  }
}

class Item extends StatelessWidget {
  String title;
  Widget child;

  Item({required this.title, required this.child});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: MyColor.White,
      margin: EdgeInsets.only(bottom: 1),
      child: Row(children: [
        Container(
          padding: EdgeInsets.all(14),
          width: 120,
          child: Text(title, style: TextStyle(fontSize: 14, color: MyColor.Black, fontWeight: FontWeight.bold, letterSpacing: 2)),
        ),
        Expanded(child: child)
      ]),
    );
  }
}

class SexChooser extends StatelessWidget {
  static String Male = "Male";
  static String Female = "Female";
  String sex;
  Function(String sex) onSexChoose;

  SexChooser({required this.sex, required this.onSexChoose});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        GestureDetector(
          onTap: () {
            onSexChoose(Male);
          },
          behavior: HitTestBehavior.opaque,
          child: Container(
              height: 40, child: Row(children: [Check(sex == Male), Text(" 男 ", style: TextStyle(fontSize: 14, color: MyColor.C58))])),
        ),
        Container(width: 24),
        GestureDetector(
          onTap: () {
            onSexChoose(Female);
          },
          behavior: HitTestBehavior.opaque,
          child: Container(
              height: 40, child: Row(children: [Check(sex == Female), Text(" 女 ", style: TextStyle(fontSize: 14, color: MyColor.C58))])),
        )
      ],
    );
  }
}

class ChangePsw extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () {
          PageUtil().open(context, ChangePassword());
        },
        child: Container(
            color: MyColor.White,
            padding: EdgeInsets.all(12),
            margin: EdgeInsets.only(bottom: 1),
            child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              Container(
                width: 120,
                child: Text("變更密碼", style: TextStyle(fontSize: 14, color: MyColor.Black, fontWeight: FontWeight.bold, letterSpacing: 2)),
              ),
              LocalImage("right_arrow.png", width: 12)
            ])));
  }
}
